//
//  StatusTable.m
//  AirQuality
//
//  Created by Po on 15/5/7.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJStatusTable.h"
#import "RJStatusTableCell.h"
@interface RJStatusTable () <UITableViewDelegate, UITableViewDataSource>
@property (retain, nonatomic) UIView * explainView;                 //说明
@property (retain, nonatomic) RJLoadView * statusLoadView;

@property (retain, nonatomic) NSMutableArray * statusData;          //数据
@property (retain, nonatomic) NSDictionary * resultData;            //污染数据

@property (assign, nonatomic) NSInteger currentNum;                 //当前选中行
@property (assign, nonatomic) NSInteger earlyNum;                   //
@property (assign, nonatomic) BOOL isSameBtn;
@property (assign, nonatomic) BOOL isAnim;                          //动画
@property (assign, nonatomic) CGFloat titleHeight;                  //标题高度
@property (assign, nonatomic) CGFloat panXPointStart;               //滑动的X坐标起点

- (void)initInterface;

@end

@implementation RJStatusTable

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super init];
    if (self) {
        [self.view setFrame:frame];
        _statusData = [NSMutableArray array];
        _currentNum = -1;
        _earlyNum = -1;
        _titleHeight = 50;
        _isSameBtn = YES;
        _isAnim = NO;
        [self initInterface];
//        [self.tableView registerClass:[RJStatusTableCell class] forCellReuseIdentifier:@"statusCell"];
    }
    return self;
}

- (void)initInterface
{
    [self.view addSubview:[self getTableView]];
    [self.view addSubview:[self getTitleView]];
    
    [self.view addSubview:[self getExplainView:CGRectMake(0, 50, ScreenWidth, 30)]];

//    [self playExplainAnim];
    
    UIPanGestureRecognizer * panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(userPanFunc:)];
    [self.view addGestureRecognizer:panGesture];
}

- (UITableView *)getTableView
{
    if (!_tableView) {
        CGRect rect = self.view.frame;
        rect.origin.y = 80;
        rect.size.height -= (_titleHeight + 30);
        [self.tableView setFrame:rect];
        _tableView = [[UITableView alloc] initWithFrame:rect];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerNib:[UINib nibWithNibName:@"RJStatusTableCell" bundle:nil] forCellReuseIdentifier:@"statusCell"];
    }
    return _tableView;
}

- (UIView *)getTitleView
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, _titleHeight)];
    [view setBackgroundColor:SysMainColor];
    [view addSubview:[self getTitleLabel:CGRectMake(0, 0, ScreenWidth, _titleHeight)]];
    return view;
}

- (UILabel *)getTitleLabel:(CGRect)rect
{
    UILabel * label = [[UILabel alloc] initWithFrame:rect];
    [label setText:@"全省市州站状态"];
    [label setTextColor:[UIColor whiteColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setFont:[UIFont boldSystemFontOfSize:20]];
    return label;
}

- (UIView *)getExplainView:(CGRect)rect
{
    if (!_explainView) {
//        rect.origin.y += 6;
        _explainView = [[UIView alloc] initWithFrame:rect];
        [_explainView setBackgroundColor:GetRGBColor(245, 245, 245, 1)];
        [_explainView.layer setShadowColor:[UIColor grayColor].CGColor];
        [_explainView.layer setShadowOffset:CGSizeMake(0, 0.5)];
        [_explainView.layer setShadowOpacity:0.5];
        NSArray * images = @[@"noSendStuate",@"isSendStuate",@"noCheckStuate",@"isCheckStuate"];
        NSArray * titles = @[@"未下发",@"已下发",@"未审核",@"已审核"];
        CGFloat width = (ScreenWidth - 20) / images.count;
        for (NSUInteger i = 0; i < images.count; i ++) {
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20 + width * i, 8, 13, 13)];
            [imageView setImage:[UIImage imageNamed:images[i]]];
            [_explainView addSubview:imageView];
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20 + width * i + 20, 8, 15 * 3, 15)];
            [label setFont:[UIFont systemFontOfSize:15]];
            [label setTextColor:[UIColor blackColor]];
            [label setText:titles[i]];
            [_explainView addSubview:label];
        }
//        _explainView.clipsToBounds = YES;
    }
    return _explainView;
}

#pragma mark - function

- (void)setData:(NSDictionary *)data
{
    _resultData = [NSDictionary dictionaryWithDictionary:data[@"resultData"]];
    for (NSDictionary * dic in data[@"data"]) {
        NSString * cityName = dic[@"CITYNAME"];
        NSMutableArray * array = [NSMutableArray array];
        for (NSDictionary * station in dic[@"STATIONTYPES"]) {
            [array addObject:station[@"STATIONTYPENAME"]];
        }
        [_statusData addObject:@{cityName:@{@"stations":array,@"cityCode":dic[@"CITYCODE"]}}];
    }
    [self.tableView reloadData];
}

- (void)updateData
{
    [self showLoadView];
    NSUserDefaults * userId = [NSUserDefaults standardUserDefaults];
    NSArray * userIdArr = [userId objectForKey:@"userId1"];
    NSString * userId1 = userIdArr[0];
    NSString * userCityCode = userIdArr[1];
   [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].AllCityAndStation data:@{@"stationtype":@1,@"timepoint":[RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate],@"userId":userId1,@"cityCode":userCityCode} completeBlock:^(id responseObject) {
        [self setData:responseObject];
        [self freeLoadView];
    }failBlack:^(id response) {
        [self freeLoadView];
        if (_delegate) {
            [_delegate netRequsetFail];
        }
    }];
}

- (void)showLoadView
{
    if (!_statusLoadView) {
        _statusLoadView = [[RJLoadView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:_statusLoadView];
    }
}

- (void)freeLoadView
{
    if (_statusLoadView) {
        [_statusLoadView removeFromSuperview];
        _statusLoadView = nil;
    }
}

#pragma mark - event
- (void)userPanFunc:(UIPanGestureRecognizer *)panGestrue
{
    UIView * superView = [self.view superview];
    if (panGestrue.state == UIGestureRecognizerStateBegan) {
        _panXPointStart = [panGestrue locationInView:superView].x;
    } else if (panGestrue.state == UIGestureRecognizerStateChanged) {
        CGFloat nowXpoint = [panGestrue locationInView:superView].x;
        if (nowXpoint < _panXPointStart) {
            CGRect rect = self.view.frame;
            rect.origin.x = (nowXpoint - _panXPointStart);
            [self.view setFrame:rect];
        }
    } else {
        CGFloat lenght =  - self.view.frame.origin.x;
        if ((lenght > 100) && _delegate) {
            [_delegate RJStatusTable:self rowNum:-1 cityCode:nil];
        } else {
            CGRect rect = self.view.frame;
            rect.origin.x = 0;
            [self.view setFrame:rect];
        }
    }
}

#pragma mark - fuction
- (void)clickSection:(UIButton *)sender
{
    NSUInteger count = sender.tag - 200;
    if (_currentNum == count) {
        _currentNum = -1;
    } else {
        _currentNum = count;
    }
    [self.tableView reloadData];
}

- (void)playExplainAnim
{
    if (_isAnim) {
        return;
    }
    
    CGRect rect = _explainView.frame;
    rect.size.height = 25;
    
    CGRect tableRect = _tableView.frame;
    tableRect.origin.y += 25;
    tableRect.size.height -= 25;
    
    [UIView animateWithDuration:0.5 animations:^{
        _isAnim = YES;
        [_explainView setFrame:rect];
        [_tableView setFrame:tableRect];
    } completion:^(BOOL finished) {
        if (finished) {
            [self performSelector:@selector(hideExplainAnim) withObject:nil afterDelay:3.0];
        }
    }];
}

- (void)hideExplainAnim
{
    CGRect rect = _explainView.frame;
    CGRect tableRect = _tableView.frame;
    rect.size.height = 0;
    tableRect.origin.y -= 25;
    tableRect.size.height += 25;
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [_explainView setFrame:rect];
        [_tableView setFrame:tableRect];
    } completion:^(BOOL finished) {
        if (finished) {
            _isAnim = NO;
        }
    }];
}

- (void)clickTittleView
{
    [self playExplainAnim];
}

#pragma mark - delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber * cityCodeNum = [[_statusData[indexPath.row] allValues] lastObject][@"cityCode"];
    if (_delegate) {
        [_delegate RJStatusTable:self rowNum:indexPath.row cityCode:cityCodeNum];
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _statusData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdent = @"statusCell";
    RJStatusTableCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    NSInteger tag = 0;//是否包含pm2.5
    NSMutableAttributedString * pmArrStr;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    NSString * nameString = [_statusData[indexPath.row] allKeys][0];
    NSUInteger subsprict = [nameString rangeOfString:@"["].location;
    NSMutableString * mString = [NSMutableString stringWithString:nameString];
    [mString insertString:@"   " atIndex:subsprict];
    NSString * cityName =mString;
    NSNumber * cityCodeNum = [[_statusData[indexPath.row] allValues] lastObject][@"cityCode"];
    NSString * cityCode = [NSString stringWithFormat:@"%ld",(long)[cityCodeNum integerValue]];
    NSDictionary * cityData = _resultData[cityCode];
    [cell setCityName:cityName];
    [cell setAQiNum:cityData[@"AQI"]];
    NSString * pollutionString , *surePollutionString;
    NSString * string = cityData[@"PRIMARYPOLLUTANT"];
    if ([string rangeOfString:@"PM10"].location != NSNotFound) {
        pollutionString = [string  stringByReplacingOccurrencesOfString:@"PM10" withString:@"PM₁₀"];
    }else if ([string rangeOfString:@"PM2.5"].location != NSNotFound){
        NSInteger index = [string rangeOfString:@"2"].location;
        pmArrStr = [[NSMutableAttributedString alloc] initWithString:string];
        [pmArrStr addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:10]
                         range:NSMakeRange(index, 3)];
        [pmArrStr addAttribute:NSBaselineOffsetAttributeName
                         value:[NSNumber numberWithFloat:-3]
                         range:NSMakeRange(index, 3)];
        tag = 1;
    }else{
        pollutionString = string;
    }
    //pollutionString is nil
    if (pollutionString) {
        if ([pollutionString rangeOfString:@"PM2.5"].location != NSNotFound) {
            NSInteger index = [string rangeOfString:@"2"].location;
            pmArrStr = [[NSMutableAttributedString alloc] initWithString:string];
            [pmArrStr addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:10]
                             range:NSMakeRange(index, 3)];
            [pmArrStr addAttribute:NSBaselineOffsetAttributeName
                             value:[NSNumber numberWithFloat:-3]
                             range:NSMakeRange(index, 3)];
            tag = 1;
            //        surePollutionString = [pollutionString stringByReplacingOccurrencesOfString:@"PM2.5"  withString:@"PM₂.₅"];
        }else{
            surePollutionString = pollutionString;
        }
    }
    
    if (tag == 0) {
       [cell setPollutionString:surePollutionString];
    }else if (tag == 1){
        [cell setPollutionAttrString:pmArrStr];
    }
    NSArray * stations = [[_statusData[indexPath.row] allValues] lastObject][@"stations"];
    NSArray * stationsViews = @[cell.cityStationView, cell.countryStation, cell.directionStation];
    NSMutableArray * mutabStations = [NSMutableArray array];
    if (stations.count >= 4) {
        for (NSString * string in stations) {
            if ([string rangeOfString:@"直管站"].location == NSNotFound) {
                [mutabStations addObject:string];
            }
        }
    }else{
        mutabStations = [stations mutableCopy];
    }
    for (NSUInteger i = 0; i < mutabStations.count; i ++) {
        NSString * stationName = mutabStations[i];
        RJStatusTableCellStatus * statusView = stationsViews[i];
        [statusView setStuateText:stationName];
    }
    
    return cell;
}

#pragma mark - system

#pragma mark - 辅助方法
- (NSMutableAttributedString *)getColorTextWithStatusString:(NSString *)string
{
    NSMutableAttributedString * colorText = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range = [colorText.string rangeOfString:@"["];
    [colorText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, range.location)];
    NSUInteger start = range.location;
    NSUInteger end = colorText.string.length - start;
    NSString * status = [string substringWithRange:NSMakeRange(start, end)];
    UIColor * color = [self getColorWithStatus:status];
    [colorText addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(start, end)];
    return colorText;
}

- (UIColor *)getColorWithStatus:(NSString *)status
{
    if ([status isEqualToString:@"已下发"]) {
        return [UIColor greenColor];
    } else if([status isEqualToString:@"未下发"]) {
        return [UIColor redColor];
    } else if([status isEqualToString:@"已审核"]) {
        return [UIColor greenColor];
    } else {
        return [UIColor greenColor];
    }
}

@end
